/**
 * 停用词
 */
import {
    getItems,
    getItemById,
    createItem,
    updateItem,
    updateItems,
    deleteItem,
    directus,
} from "@/api/directus";

/** 集合名 */
export const COLLECTION_STOPWORDS = "stopwords" as const;

/** 状态 */
export type StopwordStatus = "published" | "draft" | "archived";

/** 实体 */
export interface StopwordItem {
    id: number | string;
    query: string;
    status: StopwordStatus;
    date_created?: string;
    date_updated?: string;
}

/** 列表入参 */
export interface StopwordListParams {
    page?: number;
    pageSize?: number;
    keyword?: string;
    sort?: string | string[];
    excludeStatus?: StopwordStatus | null;
    signal?: AbortSignal;
}

/** 列表返回 */
export interface StopwordListResult {
    list: StopwordItem[];
    total: number;
}

/** 导入结果 */
export interface StopwordImportResult {
    total?: number;
    inserted?: number;
    created?: number;
    updated?: number;
    skipped?: number;
    failed?: number;
    details?: any;
}

/* ======================= 工具函数 ======================= */

const FIELDS_BASE = ["id", "query", "status"] as const;
type FieldKey = (typeof FIELDS_BASE)[number];

const normalizeSort = (sort?: string | string[]) =>
    Array.isArray(sort) ? sort.filter(Boolean) : sort ? [sort] : [];

const safeTrim = (s?: string) => (typeof s === "string" ? s.trim() : "");

const buildFilter = ({
    excludeStatus,
    keyword,
    ids,
}: {
    excludeStatus?: StopwordStatus | null;
    keyword?: string;
    ids?: Array<number | string>;
}) => {
    const filter: Record<string, any> = {};
    if (excludeStatus) filter.status = { _neq: excludeStatus };
    const kw = safeTrim(keyword);
    if (kw) filter._or = [{ query: { _contains: kw } }];
    if (ids && ids.length) filter.id = { _in: ids };
    return filter;
};

/* ======================= 列表 ======================= */

/** 获取停用词列表 */
export async function fetchStopwordList(
    params: StopwordListParams = {}
): Promise<StopwordListResult> {
    const {
        page = 1,
        pageSize = 25,
        keyword = "",
        sort = ["id"],
        excludeStatus = "archived",
        signal,
    } = params;

    const res: any = await getItems<StopwordItem>(COLLECTION_STOPWORDS, {
        fields: FIELDS_BASE as unknown as FieldKey[],
        sort: normalizeSort(sort),
        page,
        limit: pageSize,
        filter: buildFilter({ excludeStatus, keyword }),
        meta: "total_count",
        signal,
    });

    const list: StopwordItem[] = (res?.data ?? []) as StopwordItem[];
    const total = res?.meta?.total_count ?? res?.meta?.filter_count ?? list.length;
    return { list, total };
}

/* ======================= 详情/新增/更新 ======================= */

/** 详情 */
export function getStopwordById(id: number | string) {
    return getItemById<StopwordItem>(COLLECTION_STOPWORDS, id, {
        fields: ["id", "query", "status", "date_created", "date_updated"],
    });
}

/** 新增 */
export function createStopword(payload: {
    query: string;
    status?: StopwordStatus;
}) {
    const data = { query: payload.query, status: payload.status ?? "published" };
    return createItem<StopwordItem>(COLLECTION_STOPWORDS, data);
}

/** 更新 */
export function updateStopword(
    id: number | string,
    payload: Partial<StopwordItem>
) {
    return updateItem<StopwordItem>(COLLECTION_STOPWORDS, id, payload);
}

/* ======================= 删除 / 批量删除 ======================= */

/** 单删 */
export function removeStopword(id: number | string) {
    return deleteItem(COLLECTION_STOPWORDS, id);
}

/** 批量删除 */
export async function batchRemoveStopwords(ids: Array<number | string>) {
    if (!ids?.length) return;
    try {
        await directus.delete(`/items/${COLLECTION_STOPWORDS}`, {
            headers: { "Content-Type": "application/json" },
            data: { keys: ids },
        });
    } catch {
        await Promise.all(ids.map((id) => deleteItem(COLLECTION_STOPWORDS, id)));
    }
}

/* ======================= 状态（启用/停用/批量） ======================= */

/** 批量更新状态 */
export function batchSetStatus(
    ids: Array<number | string>,
    status: StopwordStatus
) {
    return updateItems(COLLECTION_STOPWORDS, ids, { status });
}

/** 单个启用 => published */
export function enableStopword(id: number | string) {
    return updateStopword(id, { status: "published" });
}

/** 单个停用 => draft */
export function disableStopword(id: number | string) {
    return updateStopword(id, { status: "draft" });
}

/* ======================= 导入 ======================= */
export async function importStopwordsByFile(
    file: File | Blob,
    extra?: { format?: "csv" | "json"; overwrite?: boolean; signal?: AbortSignal; filename?: string }
): Promise<StopwordImportResult> {
    const fd = new FormData();
    const name = extra?.filename || (file instanceof File ? file.name : "stopwords.csv");
    fd.append("file", file, name);
    if (extra?.format) fd.append("format", extra.format);
    if (typeof extra?.overwrite === "boolean") fd.append("overwrite", String(extra.overwrite));

    const res: any = await directus.post(`/utils/import/stopwords`, fd, {
        signal: extra?.signal as any,
    });
    return (res?.data?.data ?? res?.data) as StopwordImportResult;
}

/** 直接传 items 导入  */
export async function importStopwordsByItems(
    items: Array<{ query: string; status?: StopwordStatus }>,
    extra?: { overwrite?: boolean; signal?: AbortSignal; chunkSize?: number }
): Promise<StopwordImportResult> {
    const chunkSize = extra?.chunkSize && extra.chunkSize > 0 ? extra.chunkSize : Infinity;
    let last: StopwordImportResult = {};
    for (let i = 0; i < items.length; i += chunkSize) {
        const slice = items.slice(i, i + chunkSize);
        const body = { items: slice, overwrite: extra?.overwrite ?? undefined };
        const res: any = await directus.post(`/utils/import/stopwords`, body, {
            signal: extra?.signal as any,
        });
        last = (res?.data?.data ?? res?.data) as StopwordImportResult;
    }
    return last;
}

/* ======================= 导出======================= */
export async function fetchStopwordsForExport(opts?: {
    ids?: Array<number | string>;
    excludeStatus?: StopwordStatus | null;
    sort?: string | string[];
    signal?: AbortSignal;
}) {
    const fields = ["query", "status"];
    const filter = buildFilter({
        excludeStatus: opts?.excludeStatus ?? "archived",
        keyword: undefined,
        ids: opts?.ids,
    });

    const res: any = await getItems<any>(COLLECTION_STOPWORDS, {
        fields,
        filter,
        sort: normalizeSort(opts?.sort ?? "id"),
        limit: -1,
        signal: opts?.signal,
    });

    return (res?.data ?? []) as Array<{ query: string; status: StopwordStatus }>;
}

/* ======================= 当前用户 ======================= */

/** 获取当前用户 */
export async function getCurrentUserId(): Promise<string | number | null> {
    const res: any = await directus.get(`/users/me`, { params: { fields: "id" } });
    const id = res?.data?.data?.id ?? res?.data?.id ?? null;
    return id;
}
